//
//  UITextView+Ext.swift
//  YiZhangGui
//
//  Created by Fexerlear on 2019/1/31.
//  Copyright © 2019 Mac. All rights reserved.
//

import UIKit


// MARK: - Enums
public extension UITextField {

    /// SwifterSwift: UITextField text type.
    ///
    /// - emailAddress: UITextField is used to enter email addresses.
    /// - password: UITextField is used to enter passwords.
    /// - generic: UITextField is used to enter generic text.
    enum TextType {
        /// SwifterSwift: UITextField is used to enter email addresses.
        case emailAddress

        /// SwifterSwift: UITextField is used to enter passwords.
        case password

        /// SwifterSwift: UITextField is used to enter generic text.
        case generic
    }

}

// MARK: - Properties
public extension UITextField {

    /// SwifterSwift: Set textField for common text types.
    var textType: TextType {
        get {
            if keyboardType == .emailAddress {
                return .emailAddress
            } else if isSecureTextEntry {
                return .password
            }
            return .generic
        }
        set {
            switch newValue {
            case .emailAddress:
                keyboardType = .emailAddress
                autocorrectionType = .no
                autocapitalizationType = .none
                isSecureTextEntry = false
                placeholder = "Email Address"

            case .password:
                keyboardType = .asciiCapable
                autocorrectionType = .no
                autocapitalizationType = .none
                isSecureTextEntry = true
                placeholder = "Password"

            case .generic:
                isSecureTextEntry = false
            }
        }
    }

    /// SwifterSwift: Check if text field is empty.
    var isEmpty: Bool {
        return text?.isEmpty == true
    }

    /// SwifterSwift: Return text with no spaces or new lines in beginning and end.
    var trimmedText: String? {
        return text?.trimmingCharacters(in: .whitespacesAndNewlines)
    }

    /// SwifterSwift: Check if textFields text is a valid email format.
    ///
    ///        textField.text = "john@doe.com"
    ///        textField.hasValidEmail -> true
    ///
    ///        textField.text = "swifterswift"
    ///        textField.hasValidEmail -> false
    ///
    var hasValidEmail: Bool {
        // http://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift
        return text!.range(of: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}",
                           options: String.CompareOptions.regularExpression,
                           range: nil, locale: nil) != nil
    }

    /// SwifterSwift: Left view tint color.
    @IBInspectable var leftViewTintColor: UIColor? {
        get {
            guard let iconView = leftView as? UIImageView else { return nil }
            return iconView.tintColor
        }
        set {
            guard let iconView = leftView as? UIImageView else { return }
            iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate)
            iconView.tintColor = newValue
        }
    }

    /// SwifterSwift: Right view tint color.
    @IBInspectable var rightViewTintColor: UIColor? {
        get {
            guard let iconView = rightView as? UIImageView else { return nil }
            return iconView.tintColor
        }
        set {
            guard let iconView = rightView as? UIImageView else { return }
            iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate)
            iconView.tintColor = newValue
        }
    }

}

// MARK: - Methods
public extension UITextField {

    /// SwifterSwift: Clear text.
//    func clear() {
//        text = ""
//        attributedText = NSAttributedString(string: "")
//    }
//
//    /// SwifterSwift: Set placeholder text color.
//    ///
//    /// - Parameter color: placeholder text color.
//    func setPlaceHolderTextColor(_ color: UIColor) {
//        guard let holder = placeholder, !holder.isEmpty else { return }
//        attributedPlaceholder = NSAttributedString(string: holder, attributes: [.foregroundColor: color])
//    }

    /// SwifterSwift: Add padding to the left of the textfield rect.
    ///
    /// - Parameter padding: amount of padding to apply to the left of the textfield rect.
//    func addPaddingLeft(_ padding: CGFloat) {
//        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: frame.height))
//        leftView = paddingView
//        leftViewMode = .always
//    }

    /// SwifterSwift: Add padding to the left of the textfield rect.
    ///
    /// - Parameters:
    ///   - image: left image
    ///   - padding: amount of padding between icon and the left of textfield
    func addPaddingLeftIcon(_ image: UIImage, padding: CGFloat) {
        let imageView = UIImageView(image: image)
        imageView.contentMode = .center
        leftView = imageView
        leftView?.frame.size = CGSize(width: image.size.width + padding, height: image.size.height)
        leftViewMode = .always
    }
    func addPaddingRightIcon(_ image: UIImage, padding: CGFloat) {
        let imageView = UIImageView(image: image)
        imageView.contentMode = .center
        rightView = imageView
        rightView?.frame.size = CGSize(width: image.size.width + padding, height: image.size.height)
        rightViewMode = .always
    }

}

extension UITextField {
    private struct RuntimeKey {
        static let hw_TextFieldKey = UnsafeRawPointer.init(bitPattern: "hw_TextField".hashValue)
        /// ...其他Key声明
    }
    /// 运行时关联
    var hw: hw_TextField {
        set {
            objc_setAssociatedObject(self, UITextField.RuntimeKey.hw_TextFieldKey!, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            var obj = objc_getAssociatedObject(self, UITextField.RuntimeKey.hw_TextFieldKey!) as? hw_TextField
            if obj == nil { // 没有是手动创建 并进行绑定
                obj = hw_TextField.init(self)
                objc_setAssociatedObject(self, UITextField.RuntimeKey.hw_TextFieldKey!, obj, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
            return obj!
        }
    }
    
}
class hw_TextField: NSObject, UITextFieldDelegate{
    weak var tf: UITextField? // 定义属性用于临时记录
    /// 值改变回调
    var valuesChangeBlock: ((String)->())?
    /// 结束编辑回调(未输入是不会回调)
    var endEditingBlock: ((String)->())?
    /// 开始编辑
    var beginEditingBlock: ((String)->())?
    /// 是否是人民币输入
    @discardableResult
    func isMoeeyEidtor(_ isMoeey: Bool) -> hw_TextField {
        isMoeeyEidtor = isMoeey
        return self
    }
    private var _isMoeeyEidtor =  false
    private var pointlocation:Int = -1 // 用于记录小数点位置
    private var isMoeeyEidtor : Bool {
        set {
            _isMoeeyEidtor = newValue
            self.tf?.keyboardType = .decimalPad
        }
        get {
            return _isMoeeyEidtor
        }
    }
    
    convenience init(_ tf: UITextField) {
        self.init()
        self.tf = tf
        self.tf?.delegate = self
        self.tf!.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
    }
    @objc private func editingChanged() {
        if valuesChangeBlock == nil {return}
        valuesChangeBlock!(tf?.text ?? "")
    }
    
    override init() {
        super.init()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if endEditingBlock == nil {return}
        endEditingBlock!(textField.text ?? "")
    }
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if beginEditingBlock == nil {return}
        beginEditingBlock!(textField.text ?? "")
    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if isMoeeyEidtor == true {
            if string == "."{ // 记录小数点位置
                pointlocation = range.location
            }
            if range.location == 0 { // 首位不能为小数点
                if string == "." { return false }
            }
            if textField.text == "0"{
                if string == "." || string == "" {
                    return true
                } else {
                    return false
                }
            }
            if (textField.text?.contains("."))! { // 包含小数点 后面不能再输入小数点
                if string == "." {  return false }
            }
            if pointlocation != -1 {
                if range.location > pointlocation + 2 {  return false } // 小数点后2位
            }
        }
        return true
    }
    deinit {
        self.tf?.delegate = nil
    }
}

